package br.com.robot.implement;

import java.awt.AWTException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import model.dao.DAOFactory;

import org.apache.http.client.ClientProtocolException;

import util.ER;
import util.Web;
import br.com.model.Game;
import br.com.robot.RobotExecutorB;

public class NewSteamRobot extends RobotExecutorB 
{
	public NewSteamRobot( ) throws AWTException 
	{
		super( );
	}

	private int totalPaginas = 0;
	
	@Override
	public void start( ) throws Exception 
	{
		String buscaExprecao = ER.buscaExprecao( Web.get( "http://store.steampowered.com/search/results?sort_order=ASC&page=1" ), 
				 "\\.\\.\\..*?<a href.*?>(.*?)</" );

		totalPaginas = Integer.parseInt( buscaExprecao );
		
		buscaProximo( 1 );
	}
	
	private void buscaProximo( final int nPag ) throws ClientProtocolException, IOException
	{
		startNewThread(  new Runnable( )
		{
			public void run( )
			{
				try
				{
					buscaExprecao( Web.get( "http://store.steampowered.com/search/results?sort_order=ASC&page=" + nPag ),
								   "class=\"col search_name ellipsis\">.*?<span class=\"title\">(.*?)</",
					               "<div class=\"col search_price .*?\">(.*?)</div>",
					               "<div class=\"col search_metascore\">(.*?)</",
					               "<div class=\"col search_released\">(.*?)</",
					               "<a href=\"(.*?)\" class=\"search_result_row.*? >", nPag );
				} 
				catch( FileNotFoundException e )
				{
					logaErro( e );
					e.printStackTrace( );
				} 
				catch( ClientProtocolException e ) 
				{
					logaErro( e );
					e.printStackTrace( );
				} 
				catch( IOException e ) 
				{
					logaErro( e );
					e.printStackTrace( );
				}
				catch( Exception e ) 
				{
					logaErro( e );
					e.printStackTrace( );
				}
			}
		} );
		
		if( nPag < totalPaginas )
			buscaProximo( nPag + 1 ); 
	}
	
	private void buscaExprecao( String strTexto, String expNome, String expPreco, String expMeta1score, String expLancamento, String expUrl, int nPag ) throws Exception
	{
		List<String[]> find = ER.findAll( strTexto, expPreco, expMeta1score, expLancamento, expNome );
		
		String         bloco = ER.buscaExprecao( strTexto, "<div></div>(.*?)class=\"search_pagination\"" );
		List<String[]> urls  = ER.findAll      ( bloco,    expUrl                                        );
		
		List<Game> games = new ArrayList<Game>( );
		Game       game;
		
		for( String[] aItens : find )
		{
			game = new Game( );
			
			if( aItens[0].contains( "<strike>" ) )
			{
				game.setPrecoAtu    ( Web.filter( ER.buscaExprecao( aItens[0], ".*?</span><br>(.*)$"          ) ) );
				game.setPrecoOrignal( Web.filter( ER.buscaExprecao( aItens[0], ".*?<strike>(.*?)</strike>.*$" ) ) );
			}
			else
			{
				game.setPrecoAtu(Web.filter( aItens[0] ));
			}
			
			game.setMetaScore ( aItens[1] );
			game.setLancamento( aItens[2] );
			game.setNome      ( aItens[3] );
			
			games.add( game );
		}
		
		for( int i = 0; i < games.size( ); i++ )
		{
			games.get( i ).setUrl       ( urls.get( i )[0] );
			games.get( i ).setDataVisita( getSession( )    );
		}
		
		if( DAOFactory.infGameDao( ).save( games ) == 1 )
		{
			logaMenssagem( String.format( "INFO: Pagina %s, registros inseridos %s", games.size( ), nPag ) );
		}
		else
		{
			logaMenssagem( "ERROR: Erro ao inserir" );
		}
	}
}